<?php


	namespace app\services\admin;

	use app\libs\enums\ApiCode;
	use app\libs\exceptions\ApiException;
	use Firebase\JWT\BeforeValidException;
	use Firebase\JWT\ExpiredException;
	use Firebase\JWT\JWT;
	use Firebase\JWT\Key;
	use Firebase\JWT\SignatureInvalidException;
	use think\Exception;

	class JWTServices
	{
		const JWTKEY = '123456';
		const JWTALG = 'HS256';

		public function signToken ($uid) {
			$payload = [
				//签发者,可空
				'iss'  => self::JWTKEY,
				//面向的用户,可空
				'aud'  => '',
				//签发时间
				'iat'  => time(),
				//生效时间,签发后3s生效,即 time() + 3;
				'nbf'  => time(),
				//过期时间
				'exp'  => time() + 200,
				//主体信息
				'data' => compact('uid')
			];

			$token = JWT::encode($payload, self::JWTKEY, self::JWTALG);

			return $token;
		}

		public function checkToken ($token) {
			try {
				//当前时间减去10s,时间留点余地
				JWT::$leeway = 10;
				$ret = JWT::decode($token, new Key(self::JWTKEY, self::JWTALG));
				$ret = objToArray($ret);

				/*$ret = json_decode(json_encode($ret), true);*/

				return $ret['data'];
			} catch (SignatureInvalidException $e) {
				throw new ApiException('签名不正确', ApiCode::NOT_LOGIN);
			} catch (BeforeValidException $e) {
				throw new ApiException('token尚未生效', ApiCode::NOT_LOGIN);
			} catch (ExpiredException $e) {
				throw new ApiException('登录信息已过期', ApiCode::NOT_LOGIN);
			} catch (Exception $e) {
				throw new ApiException('未知错误', ApiCode::NOT_LOGIN);
			}

		}

	}